import Vue from 'vue'
import VueRouter from 'vue-router'

import Layout from '@/views/layout'
import Login from '@/views/login'
import Search from '@/views/search'
import Article from '@/views/article'
import SearchResult from '@/views/search/searchResult'
import NotFound from '@/views/404'

import Edit from '@/views/layout/user/edit'

// 导入二级路由的对应组件
import Home from '@/views/layout/home'
import Qa from '@/views/layout/qa'
import Video from '@/views/layout/video'
import User from '@/views/layout/user'

// 导入vuex的store
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    // 重定向
    // redirect: '/home',
    children: [
      {
        path: '',
        component: Home,
        // 加上元信息 ==> 标识该Home组件需要被缓存起来
        meta: {
          isKeepLive: true
        }
      },
      {
        path: '/qa',
        component: Qa
      },
      {
        path: '/video',
        component: Video
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/article/:id',
    component: Article
  },
  {
    path: '/search/result',
    component: SearchResult
  },
  {
    path: '/user/edit',
    component: Edit
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

// 需要登录才可以访问的
const loginURLs = ['/user', '/user/edit']
// console.log(loginURLs)

// 注册全局导航守卫 ==> 拦截未登录的用户去登录
// 每一次的路由跳转会触发导航守卫
router.beforeEach((to, from, next) => {
  // console.log('从哪里来', from)
  // console.log('到哪里去', to)
  // next() // next 是个函数，需要进行调用

  // 分析步骤
  //  1. 判断是否有token
  //  2. 如果有就直接放行  next()
  //  3. 如果没有
  //    3.1 去哪里  /  /qa  /video  直接放行  next()
  //    3.2 /user  拦截去登录

  // 1.
  const token = store.state.user.token.token
  // console.log(token)

  // 2.
  if (token) {
    // 有token
    next()
  } else {
    // 没有token
    // 继续判断
    if (loginURLs.some(item => item === to.path)) {
      // if成立，说明to.path 就是你要去的路由是需要进行登录才能访问的
      // router.push('/login') // 没有带上回来的路

      router.push({
        path: '/login',
        query: {
          back: to.fullPath
        }
      })
    } else {
      // 不需要登录
      next()
    }
  }
})

export default router
